from core.models import Document as DocumentModel


class DocumentService:

    @staticmethod
    async def insert_or_update(document_data: dict):
        """
        插入或更新文档片段
        """
        document_id = document_data.get("document_id")
        content = document_data["content"]
        category = document_data["category"]
        if document_id:
            # 更新逻辑
            doc = await DocumentModel.filter(id=document_id, deleted=False).first()
            if not doc:
                return None, "未找到指定的文档片段"
            if doc.content:
                doc.content = f"{doc.content}\n{content}"
            else:
                doc.content = content
            await doc.save()
            return doc.id, None
        else:
            # 插入逻辑
            doc = await DocumentModel.create(content=content, category=category)
            return doc.id, None

    @staticmethod
    async def get_document(document_id: int):
        """
        根据ID获取文档信息
        """
        doc = await DocumentModel.filter(id=document_id, deleted=False).first()
        if not doc:
            return None
        return {
            "document_id": doc.id,
            "content": doc.content,
            "category": doc.category,
            "created_at": doc.created_at,
            "update_at": doc.update_at,
        }